<?php
declare(strict_types=1);

namespace App\Controller\Api\V1\PositionSupervise;

use App\Controller\Api\BaseController;
use App\Model\PointPosition;
use App\Model\PositionSupervise;
use App\Repositories\PointPositionRepository;
use App\Repositories\PositionPaperRepository;
use App\Repositories\PositionSuperviseRepository;
use App\Repositories\PositionSuperviseSheetRepository;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;

class PaperController extends BaseController{
    public function detail(){
        $category_id = $this->request->input('category_id',0);
        if(!$category_id){
            return $this->response->error(10014,'请正确传入分类id');
        }
        $papers = PositionPaperRepository::getInstance()->getList(['id','question','input_type','options','standard'],[[
            'field' => 'category_id',
            'value' => $category_id
        ]],false,[['field'=>'listorder','sort'=>'asc']]);
        return $this->response->success($papers);
    }

    public function submit(){
        $user = $this->request->getAttribute('user');
        $position_id = $this->request->input('position_id',0);
        $position  = PointPositionRepository::getInstance()->getById($position_id);
        if(!$position){
            return $this->response->error(10404,'点位不存在');
        }
        $lng = $this->request->input('lng',0);
        $lat = $this->request->input('lat',0);
        $answer = $this->request->input('answer',[]);
        $mask_txt = $this->request->input('mask_txt',null);
//        $arr=[[
//            'id' => 1,
//            'answer_txt'=>'符合',
//            'extend_images'=>'http://www.baidu.com/1.jpg,http://www.baidu.com/2.jpg',
//            'extend_txt' => '文本'
//        ]];
        $answer = json_decode($answer,true);
        $paper = PositionPaperRepository::getInstance()->all('*',[[
            'field' => 'category_id',
            'value' => $position->category_id
        ]]);
        if(!$paper->count()){
            return $this->response->error(11404,'点位问卷不存在');
        }
        $paper = $paper->keyBy('id');
        if($paper->count()!=count($answer)){
            return $this->response->error(11415,'问卷未答完');
        }
        DB::beginTransaction();
        try{
            $result = PositionSuperviseRepository::getInstance()->store([
                'id' => 0,
                'user_id' => $user->id,
                'position_id' => $position_id,
                'status' => PositionSupervise::STATUS_WAITING,
                'lng' => $lng,
                'lat' => $lat,
                'mask_txt' => $mask_txt
            ]);
            if(!$result['success']){
                throw new \Exception('监督数据创建失败');
            }
            $supervise = $result['data'];
            $all_score = 0;
            $full_score = 0;
            $is_all_finish=true;
            foreach ($answer as $key=>$item){
                $image_arr=[];
                $question = $paper[$item['id']];
                $full_score+=$question->score;
                if($item['answer_txt']=='不符合'){
                    $is_all_finish=false;
                }
                if($item['answer_txt']=='不符合'&&$item['extend_images']==''){
                    throw new \Exception('不符合项未上传图片');
                }
                $item_score = $item['answer_txt']=='符合'?$question->score:0;
                $all_score+=$item_score;
                if(isset($item['extend_images'])){
                    $image_arr = explode(',',$item['extend_images']);
                    foreach($image_arr as &$img){
                        $img=str_replace(env('QINBIU_DOMAIN'),'',$img);
                    }
                }
                $insert_data=[
                    'id' => 0,
                    'supervise_id' => $supervise->id,
                    'paper_id' => $item['id'],
                    'question' => $question->question,
                    'options' => $question->options,
                    'answer_txt' => $item['answer_txt'],
                    'extend_images' => isset($item['extend_images'])?implode(',',$image_arr):null,
                    'extend_txt' => isset($item['extend_txt'])?$item['extend_txt']:null,
                    'score' => $item_score,
                    'lat' => isset($item['lat'])?$item['lat']:null,
                    'lng' => isset($item['lng'])?$item['lng']:null,
                    'address' => isset($item['address'])?$item['address']:null
                ];
                $result_answer = PositionSuperviseSheetRepository::getInstance()->store($insert_data);
                if(!$result_answer['success']){
                    throw new \Exception('答题记录保存失败');
                }
            }
            $supervise->allscore = $all_score;
            $supervise->final_score = $all_score;
            $supervise->full_score = $full_score;
            if($is_all_finish){
                $supervise->status = PositionSupervise::STATUS_DONE;
            }
            if(!$supervise->save()){
                throw new \Exception('问卷得分更新失败');
            }
            DB::commit();
        }catch (\Throwable $e){
           DB::rollBack();
           return $this->response->error(11414,$e->getMessage());
        }
        return $this->response->success(['id' => $supervise->id]);
    }

    public function  mine(){
        $user = $this->request->getAttribute('user');
        $rows = $this->request->input('rows',10);
        $search=[
            'user_id' => ['field'=>'user_id','value'=>$user->id],
        ];
        $orderBy=[[
            'field' => 'id',
            'sort' => 'desc'
        ]];
        $columns='*';
        $return = PositionSuperviseRepository::getInstance()->getList($columns,$search,['limit'=>$rows],$orderBy);
        if(!empty($return['result'])){
            foreach ($return['result'] as &$result){
                $position = PointPosition::query()->with(['category','district'])->find($result['position_id']);
                $result['name'] = date('Ymd',strtotime($result['created_at'])).'-'.object_get($position,'name').'-'.object_get($position,'district.name').'-'.object_get($position,'category.name').'-'.'考察记录';
                $count_right = PositionSuperviseSheetRepository::getInstance()->count('id',[[
                    'field' => 'supervise_id',
                    'value' => $result['id']
                ],[
                    'field' => 'answer_txt',
                    'value' => '符合'
                ]]);
                $count_wrong = PositionSuperviseSheetRepository::getInstance()->count('id',[[
                    'field' => 'supervise_id',
                    'value' => $result['id']
                ],[
                    'field' => 'answer_txt',
                    'value' => '不符合'
                ]]);
                $result['count_right'] = $count_right;
                $result['count_wrong'] = $count_wrong;
            }
        }
        return $this->response->success($return);
    }

    public function answerDetail(){
        $user = $this->request->getAttribute('user');
        $id = $this->request->input('id',0);
        $supervise = PositionSuperviseRepository::getInstance()->getById($id);
        if(!$supervise){
            return $this->response->error(1404,'数据不存在');
        }
        if($supervise->user_id!=$user->id){
            return $this->response->error(1404,'数据不存在');
        }
        $questions = PositionSuperviseSheetRepository::getInstance()->all('*',[[
            'field' => 'supervise_id',
            'value' => $id
        ]]);
        foreach ($questions as &$question){
            if($question->extend_images){
                $images = explode(',',$question->extend_images);
                $images = collect($images)->map(function($image){
                    return env('QINBIU_DOMAIN').$image;
                });
                $question->extend_images = implode(',',$images->toArray());
            }
            if($question->reply_images){
                $images = explode(',',$question->reply_images);
                $images=collect($images)->map(function($image){
                    return env('QINBIU_DOMAIN').$image;
                });
                $question->reply_images =implode(',',$images->toArray());
            }
        }
        $supervise['paper'] = $questions;
        return $this->response->success($supervise);
    }
}